package com.example.demo.Controller;

import com.example.demo.Entity.SysUser;
import com.example.demo.Service.SysUserService;
import com.example.demo.Vo.RegisterForm;
import com.example.demo.util.UserUtil;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(SysUser user,Model model){

        user.setPassword(UserUtil.encrptPassword(user.getPassword(),sysUserService.findSaltByUsername(user.getUsername())));
        return UserUtil.userLogin(user,model);
    }

    @RequestMapping("/403")
    public String unauthorizedRole(){
        return "403";
    }

    @GetMapping("/register")
    public String register(Model model){
        model.addAttribute("RegisterForm",new RegisterForm());
        return "register";
    }

    @PostMapping("/register")
    public String adduser(@ModelAttribute RegisterForm registerForm, Model model){
        String username=registerForm.getUsername();
        String password=registerForm.getPassword();
       String repassword=registerForm.getRepassword();
        if(StringUtils.isEmptyOrWhitespace(password)||StringUtils.isEmptyOrWhitespace(repassword)||StringUtils.isEmptyOrWhitespace(username)){
            model.addAttribute("error","信息不全");
        }else if(!StringUtils.equals(password,repassword)){
            model.addAttribute("error","两次密码输入不一致");
        }else if(sysUserService.hasUser(username)){
            model.addAttribute("error","用户名已注册");
        }else{
            String salt=new SecureRandomNumberGenerator().nextBytes().toHex();
            String result=UserUtil.encrptPassword(password,salt);

            sysUserService.addUser(username,result,salt);
            return UserUtil.userLogin(sysUserService.findByUsername(username),model);
        }
        model.addAttribute("RegisterForm",new RegisterForm());
        return "register";
    }
}
